<template>
  <div class="common-container" style="min-height: calc(100vh - 60px)">
    <!-- 收藏商品列表 -->
    <div class="common-content">
      <div v-for="item in collectList" :key="item.id" class="collect-item">
        <div class="item-content" @click="viewGoodsDetail(item.goodsId)">
          <img :src="item.goodsImg" alt="" class="goods-img">
          <div class="goods-info">
            <div class="goods-name">{{ item.goodsName }}</div>
            <div class="goods-price">¥{{ item.price }}</div>
            <div class="goods-desc">{{ item.description }}</div>
            <div class="collect-time">收藏时间: {{ formatDate(item.createTime) }}</div>
          </div>
        </div>
        <div class="item-actions">
          <el-button @click="addToCart(item.goodsId, 1)" type="primary" size="small" style="margin-right: 10px;">
            加入购物车
          </el-button>
          <el-button @click="removeCollect(item.id)" type="danger" size="small">
            取消收藏
          </el-button>
        </div>
      </div>
    </div>
    
    <!-- 分页 -->
    <div class="pagination-container">
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="currentPage"
        :page-sizes="[10, 20, 50, 100]"
        :page-size="pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
      >
      </el-pagination>
    </div>
    
    <!-- 空状态 -->
    <div v-if="collectList.length === 0 && !loading" class="empty-state">
      <el-empty description="暂无收藏商品"></el-empty>
      <el-button type="primary" @click="goToGoodsList" style="margin-top: 20px">
        去逛逛
      </el-button>
    </div>
    
    <!-- 加载中 -->
    <div v-loading="loading" class="loading-container" element-loading-text="加载中..."></div>
  </div>
</template>

<script>
export default {
  name: "Collect",
  data() {
    return {
      collectList: [],
      currentPage: 1,
      pageSize: 10,
      total: 0,
      loading: false
    };
  },
  created() {
    this.loadCollectList();
  },
  methods: {
    loadCollectList() {
      this.loading = true;
      
      this.request.get("/collect/page", {
        params: {
          pageNum: this.currentPage,
          pageSize: this.pageSize
        }
      }).then(res => {
        this.loading = false;
        
        if (res.code === 200) {
          // 处理返回数据格式，确保与页面展示字段一致
          this.collectList = (res.data.records || []).map(item => ({
            id: item.id,
            goodsId: item.goodsId, // 与后端保持一致使用goodsId
            goodsImg: item.img, // 映射商品图片
            goodsName: item.name, // 映射商品名称
            price: item.price, // 映射商品价格
            description: item.description, // 映射商品描述
            createTime: item.createTime // 映射收藏时间
          }));
          this.total = res.data.total || 0;
        } else {
          this.$message.error(res.msg || '获取收藏列表失败');
        }
      }).catch(() => {
        this.loading = false;
        this.$message.error('获取收藏列表失败');
      });
    },
    
    removeCollect(collectId) {
      this.$confirm('确定要取消收藏该商品吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.request.delete(`/collect/${collectId}`).then(res => {
          if (res.code === 200) {
            this.$message.success('取消收藏成功');
            // 重新加载收藏列表
            this.loadCollectList();
          } else {
            this.$message.error(res.msg || '取消收藏失败');
          }
        }).catch(() => {
          this.$message.error('取消收藏失败');
        });
      }).catch(() => {
        // 用户取消操作
      });
    },
    
    viewGoodsDetail(goodsId) {
      this.$router.push(`/front/goodsDetail/${goodsId}`);
    },
    
    addToCart(goodsId, quantity) {
      const user = JSON.parse(localStorage.getItem('user'));
      if (!user) {
        this.$message.warning('请先登录');
        this.$router.push('/login');
        return;
      }
      
      // 查找商品信息
      const collectItem = this.collectList.find(item => item.goodsId === goodsId);
      if (!collectItem) {
        this.$message.error('找不到商品信息');
        return;
      }
      
      this.request.post("/cart", {
        userId: user.id,
        goodsId: goodsId,
        goodsName: collectItem.goodsName,
        price: collectItem.price,
        num: quantity,
        total: collectItem.price * quantity
      }).then(res => {
        if (res.code === 200) {
          this.$message.success('已添加到购物车');
        } else {
          this.$message.error(res.msg || '添加购物车失败');
        }
      }).catch(() => {
        this.$message.error('添加购物车失败');
      });
    },
    
    goToGoodsList() {
      this.$router.push('/front/goodsList');
    },
    
    handleSizeChange(size) {
      this.pageSize = size;
      this.currentPage = 1;
      this.loadCollectList();
    },
    
    handleCurrentChange(current) {
      this.currentPage = current;
      this.loadCollectList();
    },
    
    formatDate(date) {
      if (!date) return '';
      return new Date(date).toLocaleDateString('zh-CN');
    }
  }
};
</script>

<style scoped>
.common-container {
  padding: 0;
}

.common-content {
  margin-bottom: 20px;
}

.collect-item {
  background-color: #fff;
  margin-bottom: 20px;
  padding: 20px;
  border-radius: 4px;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.item-content {
  display: flex;
  align-items: center;
  flex: 1;
  cursor: pointer;
}

.goods-img {
  width: 120px;
  height: 120px;
  object-fit: cover;
  margin-right: 20px;
}

.goods-info {
  flex: 1;
}

.goods-name {
  color: #303133;
  font-size: 16px;
  margin-bottom: 10px;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.goods-price {
  color: #f56c6c;
  font-weight: bold;
  font-size: 18px;
  margin-bottom: 10px;
}

.goods-desc {
  color: #606266;
  font-size: 14px;
  margin-bottom: 10px;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.collect-time {
  color: #909399;
  font-size: 12px;
}

.item-actions {
  display: flex;
  flex-direction: column;
  gap: 10px;
}

.pagination-container {
  display: flex;
  justify-content: flex-end;
  margin-top: 20px;
}

.empty-state {
  text-align: center;
  padding: 60px 0;
  background-color: #fff;
  border-radius: 4px;
}

.loading-container {
  background-color: #fff;
  padding: 40px;
  text-align: center;
}
</style>